package com.cn.kehong.service;


import com.alibaba.fastjson.JSONObject;
import com.cn.kehong.api.IProductPackageService;
import com.cn.kehong.api.IProductPeiTouService;
import com.cn.kehong.api.ISysItemService;
import com.cn.kehong.api.ISystemLogService;
import com.cn.kehong.conf.Config;
import com.cn.kehong.dao.*;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class ProductPackageServiceImpl implements IProductPackageService {
    @Autowired
    private ProductPackageMapper productPackageMapper;
    @Autowired
    private ProductPackageJobMapper productPackageJobMapper;

    @Autowired
    private ProductPackageFenjiMapper productPackageFenjiMapper;

    @Autowired
    private ProductPeiTouMapper productPeiTouMapper;

    @Autowired
    private IProductPeiTouService productPeiTouService;

    @Autowired
    private ProductThinPeriodMapper productThinPeriodMapper;
    @Autowired
    private ProductThickPeriodMapper productThickPeriodMapper;

    @Autowired
    private ProductChuciPeriodMapper productChuciPeriodMapper;

    @Autowired
    private ProductGzPeriodMapper productGzPeriodMapper;

    @Autowired
    private ProductSaojieJobMapper productSaojieJobMapper ;
    @Autowired
    private Config config;

    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    private ProductDianciPeriodMapper productDianciPeriodMapper;

    @Autowired
    private ISysItemService sysItemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private XunjianTaskMapper xunjianTaskMapper;

    @Autowired
    private ProductReworkMapper productReworkMapper;
    @Override
    public List<ProductPackageVo> getProductPackageList(QueryForm queryForm) throws Exception {
        // 获取当前班次
//        queryForm.setBanCi(getShiftType());
        int count = productPackageMapper.getProductPackageCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<ProductPackageVo> productPackageList = productPackageMapper.getProductPackageList(queryForm);
        for (ProductPackageVo packageVo :productPackageList){
            String banCi = StringUtils.equals(packageVo.getBanCi(), "1") ? "A" : "B";
            packageVo.setBanCi(banCi);
            //包装数量（标签类型是B的）
            ProductPackageJobExample example = new ProductPackageJobExample();
            example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andLabelTypeEqualTo("B").andProductPackageIdEqualTo(packageVo.getId());
            int bzNum = productPackageJobMapper.countByExample(example);
            packageVo.setCompleteNum(String.valueOf(bzNum));
            //包标数量
            ProductPackageJobExample example1 = new ProductPackageJobExample();
            example1.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andLockPackageEqualTo("1").andProductPackageIdEqualTo(packageVo.getId());
            int bbNum = productPackageJobMapper.countByExample(example1);
            packageVo.setTheoryNum(String.valueOf(bbNum));
            //产量（包装数量）*500
            double output = ((double) bzNum * 500) / 1000;
            packageVo.setBatchOutput(String.valueOf(output));
        }
//        //生产批次
//        double sumProduction = 0;
//        //标识数量
//        double sumIdentification = 0;
//        //批次产量
//        double sumBatchOutput = 0;
//        //包装数量
//        double sumPackaging = 0;
//        for (ProductPackageVo productPackageVo : productPackageList) {
//            if (productPackageVo != null) {
//                ProductPackageJobExample jobExample = new ProductPackageJobExample();
//                jobExample.createCriteria().andProductPackageIdEqualTo(productPackageVo.getId());
//                int i = productPackageJobMapper.countByExample(jobExample);
//                sumProduction += i;
//
//                String theoryNum = productPackageVo.getTheoryNum();
//                if (theoryNum != null && !theoryNum.trim().isEmpty()) {
//                    sumIdentification += Double.parseDouble(theoryNum);
//                }
//
//                String batchOutput = productPackageVo.getBatchOutput();
//                if (batchOutput != null && !batchOutput.trim().isEmpty()) {
//                    sumBatchOutput += Double.parseDouble(batchOutput);
//                }
//
//                String completeNum = productPackageVo.getCompleteNum();
//                if (completeNum != null && !completeNum.trim().isEmpty()) {
//                    sumPackaging += Double.parseDouble(completeNum);
//                }
//            }
//        }
//        if (!productPackageList.isEmpty()) {
//            productPackageList.get(0).setCount(count);
//            productPackageList.get(0).setSumProduction((int) sumProduction);
//            productPackageList.get(0).setSumIdentification((int) sumIdentification);
//            productPackageList.get(0).setSumBatchOutput((int) sumBatchOutput);
//            productPackageList.get(0).setSumPackaging((int) sumPackaging);
//        }
        return productPackageList;
    }

    @Override
    public List<ProductPackageVo> getPackageListByType(QueryForm queryForm) throws Exception {
        //批次
        if (queryForm.getStatus().equals("0")) {
            int count = productPackageMapper.getBatchCount(queryForm);
            if (count == 0) {
                return Lists.newArrayList();
            }
            List<ProductPackageVo> productPackageList = productPackageMapper.getBatchList(queryForm);
            for (ProductPackageVo packageVo :productPackageList){
                String banCi = StringUtils.equals(packageVo.getBanCi(), "1") ? "A" : "B";
                packageVo.setBanCi(banCi);
                //包装数量（标签类型是B的）
                ProductPackageJobExample example = new ProductPackageJobExample();
                example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andLabelTypeEqualTo("B").andProductPackageIdEqualTo(packageVo.getId());
                int bzNum = productPackageJobMapper.countByExample(example);
                packageVo.setCompleteNum(String.valueOf(bzNum));
                //包标数量
                ProductPackageJobExample example1 = new ProductPackageJobExample();
                example1.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andLockPackageEqualTo("1").andProductPackageIdEqualTo(packageVo.getId());
                int bbNum = productPackageJobMapper.countByExample(example1);
                packageVo.setTheoryNum(String.valueOf(bbNum));
                //产量（包装数量）*500
                double output = ((double) bzNum * 500) / 1000;
                packageVo.setBatchOutput(String.valueOf(output));
            }
            productPackageList.get(0).setCount(count);
            return productPackageList;
            //单包
        } else if (queryForm.getStatus().equals("1")) {
            int count = productPackageMapper.getSinglePackageCount(queryForm);
            if (count == 0) {
                return Lists.newArrayList();
            }
            List<ProductPackageVo> productPackageList = productPackageMapper.getSinglePackageList(queryForm);
            for (ProductPackageVo packageVo :productPackageList){
                String banCi = StringUtils.equals(packageVo.getBanCi(), "1") ? "A" : "B";
                packageVo.setBanCi(banCi);
            }
            productPackageList.get(0).setCount(count);
            return productPackageList;

        }
        return null;

    }

    @Override
    public void exportProductPackage(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String, Object> result = Maps.newHashMap();
        //批次
        if (queryForm.getStatus().equals("0")) {

            List<ProductPackageVo> productPackageList = productPackageMapper.getBatchList(queryForm);
            result.put("package", productPackageList);
            String fileName = CommonUtil.generateRandomNum("bzpc-") + ".xlsx";
            String filePath = config.filePath + fileName;
            TemplateExcelUtils.downLoadExcel(filePath, "包装明细(批次).xlsx", result, "bzpc.xlsx", response);
            //单包
        } else if (queryForm.getStatus().equals("1")) {
            List<ProductPackageVo> productPackageList = productPackageMapper.getSinglePackageList(queryForm);
            for (ProductPackageVo packageVo :productPackageList){
                String banCi = StringUtils.equals(packageVo.getBanCi(), "1") ? "A" : "B";
                packageVo.setBanCi(banCi);
            }
            String endTime = queryForm.getEndTime();
            if (endTime != null && !endTime.isEmpty()) {
                endTime = endTime.split(" ")[0]; // 切割字符串，保留日期部分
            }
            result.put("startTime", queryForm.getStartTime());
            result.put("endTime", endTime);
            result.put("package", productPackageList);
            result.put("name", queryForm.getName());
            result.put("time", queryForm.getQueryTime());
            String fileName = CommonUtil.generateRandomNum("dbbz-") + ".xlsx";
            String filePath = config.filePath + fileName;
            TemplateExcelUtils.downLoadExcel(filePath, "包装明细(单包).xlsx", result, "dbbz.xlsx", response);
        }

    }

    @Override
    public Map<String, Object> getPackageList(QueryForm queryForm) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String productCode = queryForm.getProductCode();
        ProductPackageExample example = new ProductPackageExample();
        example.createCriteria().andProductCodeEqualTo(productCode);
        List<ProductPackage> productPackages = productPackageMapper.selectByExample(example);
        //页面包装需要的数据
        result.put("productPackages", productPackages);

        //MA混料Mb干燥。。。。需要用ProductPackageJob中的product_code
        ProductPackageJobExample jobExample = new ProductPackageJobExample();
        jobExample.createCriteria().andProductPackageIdEqualTo(productPackages.get(0).getId());
        List<ProductPackageJob> productPackageJobs = productPackageJobMapper.selectByExample(jobExample);
        result.put("productPackageJobs", productPackageJobs);
        return result;
    }

    @Override
    public Map<String, Object> getPackageJobList(List<ProductPackage> ProductPackages) throws Exception {
        Map<String, Object> result = new HashMap<>();
        ArrayList<ProductPeiTou> arrayList = new ArrayList<>();
        ArrayList<ProductPeiTou> arrayList1 = new ArrayList<>();
        ArrayList<ProductThinPeriod> arrayList2 = new ArrayList<>();
        ArrayList<ProductThickPeriod> arrayList3 = new ArrayList<>();
        ArrayList<ProductChuciPeriod> arrayList4 = new ArrayList<>();
        ArrayList<ProductGzPeriod> arrayList5 = new ArrayList<>();
        ArrayList<ProductSaojieJob> arrayList6 = new ArrayList<>();
        ArrayList<ProductDianciPeriod> arrayList7 = new ArrayList<>();
        ProductPackageFenjiExample example = new ProductPackageFenjiExample();
        example.createCriteria().andPackageIdEqualTo(ProductPackages.get(0).getId());
        List<ProductPackageFenji> productPackageFenjis = productPackageFenjiMapper.selectByExample(example);
        for (ProductPackageFenji productPackageFenji:productPackageFenjis){
            //起批配料
            ProductPeiTouExample touExample = new ProductPeiTouExample();
            touExample.createCriteria().andProductCodeEqualTo(productPackageFenji.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS).andPeiStatusEqualTo("2");
            List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectByExample(touExample);
            if (productPeiTous.size()>0){
                arrayList.addAll(productPeiTous);
            }
            //投料混料
//            ProductPeiTouExample touExample1 = new ProductPeiTouExample();
//            touExample1.createCriteria().andProductCodeEqualTo(productPackageFenji.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS).andPeiStatusEqualTo("2");
//            List<ProductPeiTou> productPeiTous1 = productPeiTouMapper.selectByExample(touExample1);
//            if (productPeiTous1.size()>0){
//                arrayList1.addAll(productPeiTous1);
//            }
            //粗磨
            ProductThinPeriodExample productThinPeriodExample = new ProductThinPeriodExample();
            productThinPeriodExample.createCriteria().andProductCodeEqualTo(productPackageFenji.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS).andThinStatusNotEqualTo("0");
            List<ProductThinPeriod> productThinPeriods = productThinPeriodMapper.selectByExample(productThinPeriodExample);
            if (productThinPeriods.size()>0){
                arrayList2.addAll(productThinPeriods);
            }
            //细磨
            List<ProductThickPeriod> productThickPeriods = productThickPeriodMapper.selectByCode(productPackageFenji.getProductCode());
//            for (ProductThickPeriod productThickPeriod :productThickPeriods){
//                List<ProductThickPeriodTime> productThickPeriodTimes = productThickPeriod.getProductThickPeriodTimes();
//                if (productThickPeriodTimes.size()>=3){
//                    List<ProductThickPeriodTime> latestThree = productThickPeriodTimes.stream()
//                            .sorted(Comparator.comparing(ProductThickPeriodTime::getNumberTime, Comparator.reverseOrder())) // 根据numberTime降序排序
//                            .limit(3) // 取前三条
//                            .collect(Collectors.toList()); //
//                    productThickPeriod.setProductThickPeriodTimes(latestThree);
//                }
//
//            }
            if (productThickPeriods.size()>0){
                arrayList3.addAll(productThickPeriods);
            }
            //除磁
            ProductChuciPeriodExample productChuciPeriodExample = new ProductChuciPeriodExample();
            productChuciPeriodExample.createCriteria().andProductCodeEqualTo(productPackageFenji.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS).andChuciStatusNotEqualTo("0");
            List<ProductChuciPeriod> productChuciPeriods = productChuciPeriodMapper.selectByExample(productChuciPeriodExample);
            if (productChuciPeriods.size()>0){
                arrayList4.addAll(productChuciPeriods);
            }
            //干燥
            ProductGzPeriodExample productGzPeriodExample = new ProductGzPeriodExample();
            productGzPeriodExample.createCriteria().andProductCodeEqualTo(productPackageFenji.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS).andGzStatusNotEqualTo("0");
            List<ProductGzPeriod> productGzPeriods = productGzPeriodMapper.selectByExample(productGzPeriodExample);
            if (productGzPeriods.size()>0){
                arrayList5.addAll(productGzPeriods);
            }
            //烧结
            List<ProductSaojieJob> productSaojieJobs = productSaojieJobMapper.getProductSaojieJobBylist(productPackageFenji.getProductCode());
            if (productSaojieJobs.size()>0){
                arrayList6.addAll(productSaojieJobs);
            }
            //电除磁/分级
            List<ProductDianciPeriod> productDianciPeriods = productDianciPeriodMapper.selectProductDianciByCode(productPackageFenji.getProductCode());
            if (productDianciPeriods.size()>0){
                arrayList7.addAll(productDianciPeriods);
            }
        }
        result.put("productPeiTous", arrayList);
//        result.put("productPeiTous1", arrayList1);
        result.put("productThinPeriods", arrayList2);
        result.put("productThickPeriods", arrayList3);
        result.put("productChuciPeriods", arrayList4);
        result.put("productGzPeriods", arrayList5);
        result.put("productSaojiePeriods", arrayList6);
        result.put("productFenjiPeriods", arrayList7);
        return result;
    }
    @Override
    public List<ProductPackage> getPackageBatchList(QueryForm queryForm) throws Exception {
        int count = productPackageMapper.getPackageBatchCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<ProductPackage> productPackageList = productPackageMapper.getPackageBatchList(queryForm);
        for (ProductPackage productPackage : productPackageList) {
            ProductPackageFenjiExample example = new ProductPackageFenjiExample();
            example.createCriteria().andPackageIdEqualTo(productPackage.getId());
            List<ProductPackageFenji> productPackageFenjis = productPackageFenjiMapper.selectByExample(example);
            StringBuilder productCodeStr = new StringBuilder();
            for (ProductPackageFenji productPackageFenji : productPackageFenjis) {
                String productCode = productPackageFenji.getStartCode();
                if (productCodeStr.length() > 0) {
                    productCodeStr.append(", ");
                }
                productCodeStr.append(productCode);
            }
            productPackage.setProductCodeStr(productCodeStr.toString());
        }
        productPackageList.get(0).setCount(count);
        return productPackageList;
    }

    @Override
    public void exportBatch(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String,Object> result = Maps.newHashMap();
        ArrayList<ProductPeiTou> arrayList = new ArrayList<>();
        ArrayList<ProductPeiTou> arrayList1 = new ArrayList<>();
        ArrayList<ProductThinPeriod> arrayList2 = new ArrayList<>();
        ArrayList<ProductThickPeriod> arrayList3 = new ArrayList<>();
        ArrayList<ProductChuciPeriod> arrayList4 = new ArrayList<>();
        ArrayList<ProductGzPeriod> arrayList5 = new ArrayList<>();
        ArrayList<ProductSaojieJob> arrayList6 = new ArrayList<>();
        ArrayList<ProductDianciPeriod> arrayList7 = new ArrayList<>();
        String productCode = queryForm.getProductCode();
        ProductPackageExample example = new ProductPackageExample();
        example.createCriteria().andProductCodeEqualTo(productCode);
        List<ProductPackage> productPackages = productPackageMapper.selectByExample(example);
        ProductPackageJobExample jobExample = new ProductPackageJobExample();
        if (productPackages.size()>0){
            jobExample.createCriteria().andProductPackageIdEqualTo(productPackages.get(0).getId());
            List<ProductPackageJob> productPackageJobs = productPackageJobMapper.selectByExample(jobExample);
            for (ProductPackageJob productPackageJob:productPackageJobs){
                //起批配料
                ProductPeiTouExample touExample = new ProductPeiTouExample();
                touExample.createCriteria().andProductCodeEqualTo(productPackageJob.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS);
                List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectByExample(touExample);
                if (productPeiTous.size()>0){
                    arrayList.addAll(productPeiTous);
                }
                //投料混料
                ProductPeiTouExample touExample1 = new ProductPeiTouExample();
                touExample1.createCriteria().andProductCodeEqualTo(productPackageJob.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS).andTouStatusEqualTo("0");
                List<ProductPeiTou> productPeiTous1 = productPeiTouMapper.selectByExample(touExample1);
                if (productPeiTous1.size()>0){
                    arrayList1.addAll(productPeiTous1);
                }
                //粗磨
                ProductThinPeriodExample productThinPeriodExample = new ProductThinPeriodExample();
                productThinPeriodExample.createCriteria().andProductCodeEqualTo(productPackageJob.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS);
                List<ProductThinPeriod> productThinPeriods = productThinPeriodMapper.selectByExample(productThinPeriodExample);
                if (productThinPeriods.size()>0){
                    arrayList2.addAll(productThinPeriods);
                }
                //细磨  需要判断子表数据productThickPeriodTimes中有几条，如果大于三条，需要取numberTime是最新的来作为第三条
                List<ProductThickPeriod> productThickPeriods = productThickPeriodMapper.selectByCode(productPackageJob.getProductCode());
                for (ProductThickPeriod productThickPeriod :productThickPeriods){
                    List<ProductThickPeriodTime> productThickPeriodTimes = productThickPeriod.getProductThickPeriodTimes();
                    if (productThickPeriodTimes.size()>=3){
                        List<ProductThickPeriodTime> latestThree = productThickPeriodTimes.stream()
                                .sorted(Comparator.comparing(ProductThickPeriodTime::getNumberTime, Comparator.reverseOrder())) // 根据numberTime降序排序
                                .limit(3) // 取前三条
                                .collect(Collectors.toList()); //
                        productThickPeriod.setProductThickPeriodTimes(latestThree);
                    }

                }
                if (productThickPeriods.size()>0){
                    arrayList3.addAll(productThickPeriods);
                }
                //除磁
                ProductChuciPeriodExample productChuciPeriodExample = new ProductChuciPeriodExample();
                productChuciPeriodExample.createCriteria().andProductCodeEqualTo(productPackageJob.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS);
                List<ProductChuciPeriod> productChuciPeriods = productChuciPeriodMapper.selectByExample(productChuciPeriodExample);
                if (productChuciPeriods.size()>0){
                    arrayList4.addAll(productChuciPeriods);
                }
                //干燥
                ProductGzPeriodExample productGzPeriodExample = new ProductGzPeriodExample();
                productGzPeriodExample.createCriteria().andProductCodeEqualTo(productPackageJob.getProductCode()).andStatusNotEqualTo(Constants.DEL_STATUS);
                List<ProductGzPeriod> productGzPeriods = productGzPeriodMapper.selectByExample(productGzPeriodExample);
                if (productGzPeriods.size()>0){
                    arrayList5.addAll(productGzPeriods);
                }
                //烧结
                List<ProductSaojieJob> productSaojieJobs = productSaojieJobMapper.getProductSaojieJobBylist(productPackageJob.getProductCode());
                if (productSaojieJobs.size()>0){
                    arrayList6.addAll(productSaojieJobs);
                }
                //电除磁/分级
                List<ProductDianciPeriod> productDianciPeriods = productDianciPeriodMapper.selectProductDianciByCode(productPackageJob.getProductCode());
                if (productDianciPeriods.size()>0){
                    arrayList7.addAll(productDianciPeriods);
                }
            }
            result.put("node", productPackages.get(0));
            result.put("productPackageJobs", productPackageJobs);
            result.put("productPeiTous", arrayList);
            result.put("productPeiTous1", arrayList1);
            result.put("productThinPeriods", arrayList2);
            result.put("productThickPeriods", arrayList3);
            result.put("productChuciPeriods", arrayList4);
            result.put("productGzPeriods", arrayList5);
            result.put("productSaojiePeriods", arrayList6);
            result.put("productDianciPeriods", arrayList7);
            String fileName = CommonUtil.generateRandomNum("pczsgc-")+".xlsx";
            String filePath = config.filePath+fileName;
            TemplateExcelUtils.downLoadExcel(filePath,"批次追溯(过程).xlsx",result,"pczsgc.xlsx", response);
        }
    }
    @Override
    public ProductPackage getProductPackageByRoom(QueryForm queryForm) throws Exception {
        List<ProductPackage> productPackages = productPackageMapper.selectProductPackageByRoom(queryForm);
        if (CollectionsUtil.isEmpty(productPackages)) {
            return new ProductPackage();
        }
        return productPackages.get(0);
    }

    @Override
    public String addProductPackage(ProductPackage productPackage) throws Exception {
        String factoryName = productPackage.getFactoryName();
        String jizuNum = productPackage.getJizuNum();
        String packageRoom = productPackage.getPackageRoom();
        ProductPackageExample example = new ProductPackageExample();
        example.createCriteria().andFactoryNameEqualTo(factoryName).andStatusEqualTo(Constants.NORMAL_STATUS)
                .andJizuNumEqualTo(jizuNum).andPackageRoomEqualTo(packageRoom).andPackageStatusEqualTo("0");
        int count = productPackageMapper.countByExample(example);
        if(count > 0){
            return "存在未完成的包装任务！";
        }
        String id = CommonUtil.generateRandomNum("package-");
        productPackage.setId(id);
        String yearKey = generateUUID.getYearTwoStr();
        int num = generateUUID.getNumberFlag(yearKey);
        String fourNum = generateUUID.getFourNumStr(num);
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        String lastDay = Integer.toString(year % 10);
//        String packageCode = "AF"+yearKey+fourNum;
        String packageCode=productPackage.getGradeValue()+"F"+productPackage.getPackageRoom()+lastDay+productPackage.getProductCode();
        ProductPackageExample productPackageExample = new ProductPackageExample();
        productPackageExample.createCriteria().andProductCodeEqualTo(packageCode).andStatusEqualTo(Constants.NORMAL_STATUS);
        int productCode = productPackageMapper.countByExample(example);
        if(productCode > 0){
            return "生产批次已经存在！";
        }
        productPackage.setProductCode(packageCode);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = simpleDateFormat.format(new Date());
        productPackage.setPackageStartTime(startTime);
        Map<String,String> map  = CommonUtil.getOnDutyAndWhiteDay();
        productPackage.setBanCi(map.get("whiteDay"));
        count = productPackageMapper.insertSelective(productPackage);
        if(count > 0){
            XunjianTask xunjianTask = new XunjianTask();
            xunjianTask.setAttr16(id);
            xunjianTask.setFactoryName(factoryName);
            xunjianTask.setLineType("1");
            xunjianTask.setWorkProcess("包装");
            xunjianTask.setProductCode(packageCode);
            String banCi = StringUtils.equals(productPackage.getBanCi(), "1") ? "A" : "B";
            xunjianTask.setBanCi(banCi);
            xunjianTask.setTaskName("包装工序");
            xunjianTask.setFrequency("1次/批");
            xunjianTask.setId(CommonUtil.generateRandomNum("xjtask-"));
            count = xunjianTaskMapper.insertSelective(xunjianTask);
            if(count < 1){
                throw new Exception("插入巡检表异常！");
            }
        }
        List<ProductPackageJob> packageJobs = Lists.newArrayList();
        for(int i = 1;i<= 24;i++){
            ProductPackageJob job = new ProductPackageJob();
            job.setProductPackageId(id);
            job.setBaoMachineCode(productPackage.getJizuNum());
            packageJobs.add(job);
        }
        String resp = this.addBatchProductPackageJob(packageJobs);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String addBatchProductPackageJob(List<ProductPackageJob> packageJobs) throws Exception {
        if(CollectionsUtil.isEmpty(packageJobs)){
            return "数组为空";
        }
        String packageId = packageJobs.get(0).getProductPackageId();
        ProductPackage exist = productPackageMapper.selectProductPackageById(packageId);
        if(null == exist){
            return "未查询到包装信息";
        }
        if(StringUtils.equals(exist.getPackageStatus(),"1")){
            return "包装已经完成";
        }
        if(StringUtils.equals(exist.getHasBind(),"1")){
            return "包装已经绑定";
        }
        if(StringUtils.isEmpty(packageId)){
            return "缺少包装id";
        }
        int index = 1;
        for(ProductPackageJob job :packageJobs ){
            job.setId(CommonUtil.generateRandomNum("job-"));
            String jobIndex = "";
            if(index < 10){
                jobIndex+="0"+index;
            }else {
                jobIndex = index+"";
            }
            job.setJobIndex(jobIndex);
            ++index;
        }
        int count = productPackageJobMapper.batchInsertPackageJob(packageJobs);
//
//        ProductPackage update = new ProductPackage();
//        update.setHasBind("1");
//        int size = packageJobs.size();
//        String theoryNum = exist.getTheoryNum();
//        int unCompleteNum = Integer.parseInt(theoryNum) - size;
//        update.setUncompleteNum(unCompleteNum+"");
//        ProductPackageExample packageExample = new ProductPackageExample();
//        packageExample.createCriteria().andIdEqualTo(packageId);
//        count = productPackageMapper.updateByExampleSelective(update,packageExample);
//        if(count < 1){
//            throw new Exception("更新表异常！！");
//        }
        return CommonUtil.outStr(count);
    }

    @Override
    public List<ProductPackage> getProductPackageListByStatus(String factoryName) throws Exception {
        if(StringUtils.isEmpty(factoryName)){
            return Lists.newArrayList();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse("2024-12-15 00:00:00");
        ProductPackageExample example = new ProductPackageExample();
        example.createCriteria().andHasBindNotEqualTo("2").andStatusEqualTo(Constants.NORMAL_STATUS).andFactoryNameEqualTo(factoryName);
        example.setOrderByClause("create_time asc");
        List<ProductPackage> productPackages = productPackageMapper.selectByExample(example);
        //为了减少页面展示
        if(CollectionsUtil.isNotEmpty(productPackages)&& productPackages.size() > 5){
            Iterator<ProductPackage> iterator = productPackages.iterator();
            while (iterator.hasNext()){
                ProductPackage next =  iterator.next();
                if(StringUtils.equals(next.getHasBind(),"0")){
                    continue;
                }
                if(next.getCreateTime().getTime() < date.getTime() ){
                    iterator.remove();
                }
            }
        }

        return productPackages;
    }

    @Override
    public void exportRelationship(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String,Object> result = Maps.newHashMap();
        List<ProductPackage> productPackageList = productPackageMapper.getPackageBatchList(queryForm);
        for (ProductPackage productPackage :productPackageList){
            List<ProductPackageJob> packageJobs = productPackage.getProductPackageJobs();
            StringBuilder productCodeStr = new StringBuilder();
            for (ProductPackageJob productPackageJob:packageJobs){
                String productCode = productPackageJob.getProductCode();
                if (productCodeStr.length() > 0) {
                    productCodeStr.append(" ");
                }
                productCodeStr.append(productCode);
            }
            productPackage.setProductCodeStr(productCodeStr.toString());
        }
        result.put("productPackageJobs", productPackageList);
        String fileName = CommonUtil.generateRandomNum("pczsgx-")+".xlsx";
        String filePath = config.filePath+fileName;
        TemplateExcelUtils.downLoadExcel(filePath,"批次追溯(批次关系).xlsx",result,"pczsgx.xlsx", response);
    }

    @Override
    public List<ProductPackageJob> getProductPackageJobsById(String packageId) throws Exception {
        if(StringUtils.isEmpty(packageId)){
            return Lists.newArrayList();
        }
        ProductPackageJobExample example = new ProductPackageJobExample();
        example.createCriteria().andProductPackageIdEqualTo(packageId).andStatusEqualTo(Constants.NORMAL_STATUS);
        example.setOrderByClause("create_time desc");
        List<ProductPackageJob> productPackageJobs = productPackageJobMapper.selectByExample(example);
        return productPackageJobs;
    }

    @Override
    public Map<String,Integer> getProductPackageJobByFenjiIds(List<String> fenjiIds) throws Exception {
        if(CollectionsUtil.isEmpty(fenjiIds)){
            return Maps.newHashMap();
        }
        ProductPackageFenjiExample example = new ProductPackageFenjiExample();
        example.createCriteria().andFenjiIdIn(fenjiIds).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<ProductPackageFenji> jobs = productPackageFenjiMapper.selectByExample(example);
        Map<String,Integer> jobMap = Maps.newHashMap();
        for(ProductPackageFenji job:jobs){
            String fenjiId = job.getFenjiId();
            if(jobMap.containsKey(fenjiId)){
                jobMap.put(fenjiId,jobMap.get(fenjiId)+1);
            }else{
                jobMap.put(fenjiId,1);
            }
        }
        return jobMap;
    }

    @Override
    public String updateLockPackageJob(ProductPackageJob productPackageJob) throws Exception {
        String id = productPackageJob.getId();
        if(StringUtils.isEmpty(id)){
            return "id为空";
        }
        ProductPackageJob exist = productPackageJobMapper.selectProductJobById(id);
        if(null == exist){
            return "任务不存在";
        }
        if(StringUtils.equals(exist.getLockPackage(),"1")){
            return "已经锁定！";
        }
        if(StringUtils.isEmpty(productPackageJob.getLuTemp())){
            productPackageJob.setLuTemp("-28.8");
        }
        ProductPackage productPackage = productPackageMapper.selectProductPackageById(exist.getProductPackageId());
        if(null == productPackage){
            return "包装信息未找到";
        }
        String  suplierCode ="000045";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMdd");
        String productTime = simpleDateFormat.format(new Date());
        String productCode = productPackage.getProductCode();
        String printCode = productPackage.getMaterialCode()+suplierCode+productTime+productCode+exist.getJobIndex();
        productPackageJob.setLockPackage("1");
        productPackageJob.setPrintCode(printCode);
        ProductPackageJobExample example = new ProductPackageJobExample();
        example.createCriteria().andIdEqualTo(id);
        int count = productPackageJobMapper.updateByExampleSelective(productPackageJob,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateCompletePackageJob(ProductPackageJob productPackageJob) throws Exception {
        String id = productPackageJob.getId();
        if(StringUtils.isEmpty(id)){
            return "id为空";
        }
        ProductPackageJob exist = productPackageJobMapper.selectProductJobById(id);
        if(null == exist){
            return "任务不存在";
        }
        if(!StringUtils.equals(exist.getLockPackage(),"1")){
            return "任务未锁定！";
        }
        if(StringUtils.equals(exist.getJobStatus(),"1")){
            return "任务已经完成！";
        }
        productPackageJob.setJobStatus("1");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String packageTime = simpleDateFormat.format(new Date());
        productPackageJob.setPackageTime(packageTime);
        ProductPackageJobExample example = new ProductPackageJobExample();
        example.createCriteria().andIdEqualTo(id);
        int count = productPackageJobMapper.updateByExampleSelective(productPackageJob,example);
        if(count < 1){
            return "更新表异常！";
        }
        count = productPackageMapper.updateProductPackageCompleteNum(exist.getProductPackageId());
        if(count < 1){
            throw new Exception("更新表异常");
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateEndPackage(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return "主键不能为空";
        }
        ProductPackageJobExample example = new ProductPackageJobExample();
        example.createCriteria().andProductPackageIdEqualTo(id).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<ProductPackageJob> productPackageJobs = productPackageJobMapper.selectByExample(example);
        int unCompleteNum = 0;
        for(ProductPackageJob job:productPackageJobs){
            if(!StringUtils.equals(job.getJobStatus(),"1")){
               ++unCompleteNum;
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = simpleDateFormat.format(new Date());
        ProductPackage productPackage = new ProductPackage();
        productPackage.setPackageEndTime(endTime);
        productPackage.setPackageStatus("1");
        productPackage.setUncompleteNum(unCompleteNum+"");
        ProductPackageExample packageExample = new ProductPackageExample();
        packageExample.createCriteria().andIdEqualTo(id);
        int count = productPackageMapper.updateByExampleSelective(productPackage,packageExample);
        if(count < 1){
            return "更新包装表异常!";
        }
        ProductPackageFenjiExample fenjiExample = new ProductPackageFenjiExample();
        fenjiExample.createCriteria().andPackageIdEqualTo(id);
        List<ProductPackageFenji> fenjis = productPackageFenjiMapper.selectByExample(fenjiExample);
        if(CollectionsUtil.isNotEmpty(fenjis)){
            List<String> codes = Lists.newArrayList();
            for(ProductPackageFenji fenji:fenjis){
                codes.add(fenji.getProductCode());
            }
            String resp = productPeiTouService.updateEndProductPeiTouByCodes(codes);
            if(StringUtils.isNotEmpty(resp)){
                throw new Exception(resp);
            }
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String updatePackageJobCheckCode(String id,String checkCode) throws Exception {
        if(StringUtils.isEmpty(id)){
            return "id不能为空";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String checkCodeTime = simpleDateFormat.format(new Date());
        ProductPackageJob job = new ProductPackageJob();
        job.setCheckCode(checkCode);
        job.setCheckCodeTime(checkCodeTime);
        ProductPackageJobExample example = new ProductPackageJobExample();
        example.createCriteria().andIdEqualTo(id);
        int count = productPackageJobMapper.updateByExampleSelective(job,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public List<ProductPackage> getProductPackageRecentOneDay(QueryForm queryForm) throws Exception {
        List<ProductPackage> productPackages = productPackageMapper.selectProductPackageRecentOneDay(queryForm);
        if(CollectionsUtil.isEmpty(productPackages)){
            return Lists.newArrayList();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("MM-dd HH:mm");
        for(ProductPackage productPackage:productPackages){
            String packageStartTime = productPackage.getPackageStartTime();
            String packageEndTime = productPackage.getPackageEndTime();
            Date startTime = simpleDateFormat.parse(packageStartTime);
            Date endTime = simpleDateFormat.parse(packageEndTime);
            long second = (endTime.getTime() - startTime.getTime())/1000;
            String hour = NumberUtil.getPoint(second/3600.0,1);
            productPackage.setSpendTime(hour);
            productPackage.setPackageStartTime(simpleDateFormat1.format(startTime));
            productPackage.setPackageEndTime(simpleDateFormat1.format(endTime));
        }
        return productPackages;
    }

    @Override
    public List<ProductPackageJob> getProductJobsNotFinsh() throws Exception {
        List<ProductPackageJob> jobs = productPackageJobMapper.selectProductJobsNotFinsh();
        return jobs;
    }

    @Override
    public String updateProductJobLuTemp(List<ProductPackageJob> productPackageJobs) throws Exception {
        if(CollectionsUtil.isEmpty(productPackageJobs)){
            return "";
        }
        int count = productPackageJobMapper.batchUpdateProductJobLuTemp(productPackageJobs);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateFenjiPackage(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return "id为空";
        }
        ProductPackageExample example = new ProductPackageExample();
        example.createCriteria().andIdEqualTo(id);
        ProductPackage update = new ProductPackage();
        update.setHasBind("2");

        int count = productPackageMapper.updateByExampleSelective(update,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String printProductPackageJob(String jobId) throws Exception {
        ProductPackage productPackage =  productPackageMapper.selectPackageWithJobByJobId(jobId);
        if(null == productPackage){
            return "未查询到包装信息";
        }
        String factoryName = productPackage.getFactoryName();
        String packageRoom = productPackage.getPackageRoom();
        List<SysItem> sysItems = sysItemService.getMgItemByType("11");
        String ip =  "";
        for(SysItem sysItem :sysItems){
            String itemName = sysItem.getItemName();
            String itemCode = sysItem.getItemCode();
            if(StringUtils.equals(itemName,factoryName) &&StringUtils.equals(itemCode,packageRoom) ){
                ip = sysItem.getItemAlias();
                break;
            }
        }
        if(StringUtils.isEmpty(ip)){
            return "厂区："+factoryName+"房间号："+packageRoom+"未配置打印机ip";
        }
        String machineCode = factoryName.split("-")[0]+factoryName.split("-")[1]+"-"+packageRoom+"-"+productPackage.getSingleJizu();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","2");
        jsonObject.put("batchCode",productPackage.getProductCode());
        jsonObject.put("batchNum",productPackage.getJobIndex());
        jsonObject.put("machineCode",machineCode);
        jsonObject.put("packageTime",productPackage.getPackageStartTime());
        jsonObject.put("packageCode",productPackage.getPrintCode());
        redisTemplate.opsForList().leftPush(ip, jsonObject.toJSONString());
        redisTemplate.expire(ip, 60, TimeUnit.SECONDS);
        return "";
    }

    @Override
    public String printProductSample(String jobId) throws Exception {
        ProductPackage productPackage =  productPackageMapper.selectPackageWithJobByJobId(jobId);
        if(null == productPackage){
            return "未查询到包装信息";
        }
        String factoryName = productPackage.getFactoryName();
//        String packageRoom = productPackage.getPackageRoom();
//        List<SysItem> sysItems = sysItemService.getMgItemByType("11");
        String ip =  "";
        if(StringUtils.equals(factoryName,"16-1")){
            ip = config.printIp161;
        }else if(StringUtils.equals(factoryName,"16-2")){
            ip = config.printIp162;
        }
//        for(SysItem sysItem :sysItems){
//            String itemName = sysItem.getItemName();
//            String itemCode = sysItem.getItemCode();
//            if(StringUtils.equals(itemName,factoryName) &&StringUtils.equals(itemCode,packageRoom) ){
//                ip = sysItem.getItemAlias();
//                break;
//            }
//        }
//        if(StringUtils.isEmpty(ip)){
//            return "厂区："+factoryName+"房间号："+packageRoom+"未配置打印机ip";
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","1");
        jsonObject.put("factoryName",factoryName);
        jsonObject.put("period","分级（包装）");
        jsonObject.put("sampleName",productPackage.getMaterialName());
        jsonObject.put("batchCode",productPackage.getProductCode());
        jsonObject.put("batchNum",productPackage.getJobIndex());
        jsonObject.put("itemName","粒度");
        jsonObject.put("time",productPackage.getCheckCodeTime());
        jsonObject.put("sampleCode",productPackage.getCheckCode());
        redisTemplate.opsForList().leftPush(ip, jsonObject.toJSONString());
        redisTemplate.expire(ip, 60, TimeUnit.SECONDS);
        return "";
    }

    @Override
    public List<ProductPackage> getCurrentProductPackageList(QueryForm queryForm) throws Exception {
        int count = productPackageMapper.selectProductPackagePeriodCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<ProductPackage> productPackages = productPackageMapper.selectProductPackagePeriods(queryForm);
        productPackages.get(0).setCount(count);
        return productPackages;
    }

    @Override
    public ProductPackage getProductPackageDetail(QueryForm queryForm) throws Exception {
        List<ProductPackage> productPackages = productPackageMapper.getProductPackageDetail(queryForm);
        if (CollectionsUtil.isEmpty(productPackages)) {
            return new ProductPackage();
        }
        return productPackages.get(0);
    }

    @Override
    public void exportPackageJobList(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String, Object> result = Maps.newHashMap();
        List<ProductPackageVo> productPackageList = productPackageMapper.getSinglePackageList(queryForm);
        result.put("package", productPackageList);
        String fileName = CommonUtil.generateRandomNum("bzdb-") + ".xlsx";
        String filePath = config.filePath + fileName;
        TemplateExcelUtils.downLoadExcel(filePath, "包装明细(单包).xlsx", result, "bzdb.xlsx", response);
    }

    @Override
    public String updatePackageJobStauts(ProductPackageJob productPackageJob) throws Exception {
        String id = productPackageJob.getId();
        if (StringUtils.isEmpty(id)) {
            return "id is null";
        }
        ProductPackageJobExample example = new ProductPackageJobExample();
        example.createCriteria().andIdEqualTo(id);
        productPackageJob.setUpdateTime(new Date());
        productPackageJob.setJobStatus("1");
        int count = productPackageJobMapper.updateByExampleSelective(productPackageJob,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public Map<String, Object> getPackageJobListByTobeApp(QueryForm queryForm) {
        Map<String, Object> resultMap = new HashMap<>();
//        ProductPackageJobExample example = new ProductPackageJobExample();
//            //单包待确认
//        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andJobStatusEqualTo("0");
//        List<ProductPackageJob> productPackageJobs = productPackageJobMapper.selectByExample(example);
       queryForm.setJobStatus("0");
        List<ProductPackageVo> productPackageList = productPackageMapper.getSinglePackageList(queryForm);
        if (productPackageList.size() > 0) {
                resultMap.put("CompletedList", productPackageList);
            } else {
                resultMap.put("CompletedList", new ArrayList<>());
            }
            //单包已完成
        queryForm.setJobStatus("1");
        List<ProductPackageVo> productPackageList1 = productPackageMapper.getSinglePackageList(queryForm);
            if (productPackageList1.size() > 0) {
                resultMap.put("isCompletedList", productPackageList1);
            } else {
                resultMap.put("isCompletedList", new ArrayList<>());
            }

        return resultMap;
    }


    @Override
    public List<ProductPackageVo> getPackageJobListByTobe(QueryForm queryForm) throws Exception {
        queryForm.setJobStatus("0");
        int count = productPackageMapper.getSinglePackageCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<ProductPackageVo> productPackageList = productPackageMapper.getSinglePackageList(queryForm);
        if (productPackageList.size()>0){
            productPackageList.get(0).setCount(count);

        }
        return productPackageList;
    }

    @Override
    public Map<String, Object> getBzDetailCode(String qrCode) throws Exception {
        Map<String, Object> map = Maps.newHashMap();
        map.put("errorMsg", "");
        if (StringUtils.isEmpty(qrCode)) {
            map.put("errorMsg", "二维码参数为空");
            return map;
        }
        if (qrCode.length() != 30) {
            map.put("errorMsg", "二维码长度不正确：" + qrCode.length());
            return map;
        }
        String pcCode = qrCode.substring(20, 28);
        String baoCode = qrCode.substring(28, 30);
//        String pcCode = "AF240005";
//        String baoCode = "01";
        ProductPackageExample packageExample = new ProductPackageExample();
        packageExample.createCriteria().andProductCodeEqualTo(pcCode);
        List<ProductPackage> productPackageList = productPackageMapper.selectByExample(packageExample);
        if (productPackageList.size()>0){
            String machineCode = productPackageList.get(0).getFactoryName().split("-")[0]+productPackageList.get(0).getFactoryName().split("-")[1]+"-"+productPackageList.get(0).getPackageRoom()+"-"+baoCode;
            ProductPackage productPackage = new ProductPackage();
            productPackage.setProductCodeStr(pcCode+"-"+baoCode);
            productPackage.setProductCode(pcCode);
            productPackage.setId(productPackageList.get(0).getId());
            productPackage.setProductName(machineCode);
            productPackage.setGradeValue(productPackageList.get(0).getGradeValue());
            productPackage.setPackageStartTime(productPackageList.get(0).getPackageStartTime());
            productPackage.setFactoryName(productPackageList.get(0).getFactoryName());
            map.put("job", productPackage);
        }else {
            map.put("errorMsg", "不存在的二维码");
            return map;
        }

        return map;
    }

    @Override
    public Map<String, Object> getProductByCode(QueryForm queryForm) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("errorMsg", "");
        List<Map<String, Object>> list = new ArrayList<>();
        ProductPackageExample packageExample = new ProductPackageExample();
        packageExample.createCriteria().andProductCodeEqualTo(queryForm.getProductCode());
        List<ProductPackage> packageList = productPackageMapper.selectByExample(packageExample);
        if (packageList.isEmpty()) {
            map.put("errorMsg", "暂无信息");
            return map;
        }
        ProductPackage productPackage = packageList.get(0);
        // 查询该包装批号绑定了多少个制程批次
        ProductPackageFenjiExample fenjiExample = new ProductPackageFenjiExample();
        fenjiExample.createCriteria().andPackageIdEqualTo(productPackage.getId()).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<ProductPackageFenji> productPackageFenjis = productPackageFenjiMapper.selectByExample(fenjiExample);
            Map<String, Object> batchInfo = new HashMap<>();
            batchInfo.put("codeList", productPackageFenjis);
            ProductReworkExample reworkExample = new ProductReworkExample();
            reworkExample.createCriteria().andProductCodeEqualTo(queryForm.getProductCode()).andStatusEqualTo(Constants.NORMAL_STATUS);
            List<ProductRework> productReworks = productReworkMapper.selectByExample(reworkExample);
            double totalBackWeight = 0;
            List<Map<String, Object>> tableList = new ArrayList<>();
            for (ProductRework rework : productReworks) {
                Map<String, Object> detail = new HashMap<>();
                detail.put("packageTime", rework.getPackageTime());
                detail.put("factoryName", rework.getFactoryName());
                detail.put("productCode", rework.getProductCode());
                detail.put("baoCode", rework.getBaoCode());
                detail.put("backWeight", rework.getBackWeight());
                detail.put("backReason", rework.getBackReason());
                detail.put("backStartTime", rework.getBackStartTime());
                detail.put("dianciCode", rework.getDianciCode());
                detail.put("backUserName", rework.getBackUserName());
                detail.put("bancCi", rework.getBancCi());
                tableList.add(detail);
                try {
                    totalBackWeight += Double.parseDouble(rework.getBackWeight());
                } catch (NumberFormatException e) {
                    totalBackWeight = 0;
                }
            }
            String reworkStatus = tableList.size() > 0 ? "有" : "无";
            batchInfo.put("reworkStatus", reworkStatus);
            batchInfo.put("startCodeCount", productPackageFenjis.size());
            batchInfo.put("weight", String.format("%.1f", totalBackWeight));
            batchInfo.put("tableList", tableList);
            list.add(batchInfo);
        map.put("packageList",packageList.get(0));
        map.put("list", list);
        return map;
    }

    @Override
    public List<JSONObject> getTodayPackageInfo() throws Exception {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        Date preDay = Date.from(yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        ProductPackageExample example = new ProductPackageExample();
        example.createCriteria().andCreateTimeBetween(preDay,new Date()).andStatusEqualTo(Constants.NORMAL_STATUS);

        String currentDutyDay = CommonUtil.getOnDutyAndWhiteDay().get("dutyDay");
        List<ProductPackage> packages = productPackageMapper.selectByExample(example);
        Map<String,Integer> resultMaps = Maps.newHashMap();
        for(ProductPackage productPackage:packages){
            String banci = productPackage.getBanCi();
            Map<String,String> dutyMap = CommonUtil.getOnDutyAndWhiteDayByTime(productPackage.getCreateTime());
            String dutyDay = dutyMap.get("dutyDay");
            if(!StringUtils.equals(dutyDay,currentDutyDay)){
                continue;
            }
            int completeNum = Integer.parseInt(productPackage.getCompleteNum());
            String key = banci+"=="+productPackage.getPackageRoom();
            if(resultMaps.containsKey(key)){
                completeNum =resultMaps.get(key)+completeNum;
            }
            resultMaps.put(key,completeNum);
        }
        List<JSONObject> jsonObjects = Lists.newLinkedList();
//        JSONObject header = new JSONObject();
//        header.put("first","");
//        header.put("name1","#1");
//        header.put("name2","#2");
//        header.put("name3","#3");
//        header.put("name4","#4");
//        header.put("name5","#5");
//        header.put("name6","#6");
//        jsonObjects.add(header);

        JSONObject data1 = new JSONObject();
        data1.put("first","A班");
        data1.put("name1",0);
        data1.put("name2",0);
        data1.put("name3",0);
        data1.put("name4",0);
        data1.put("name5",0);
        data1.put("name6",0);

        JSONObject data2 = new JSONObject();
        data2.put("first","B班");
        data2.put("name1",0);
        data2.put("name2",0);
        data2.put("name3",0);
        data2.put("name4",0);
        data2.put("name5",0);
        data2.put("name6",0);
        for(String key:resultMaps.keySet()){
            String banci = key.split("==")[0];
            String room = key.split("==")[1];
            int value = resultMaps.get(key);
            if(StringUtils.equals(banci,"1")){
                data1.put("name"+room,data1.getInteger("name"+room)+value);
            }else if(StringUtils.equals(banci,"2")){
                data2.put("name"+room,data2.getInteger("name"+room)+value);
            }
        }
        JSONObject data3 = new JSONObject();
        data3.put("first","合计");
        data3.put("name1",data1.getInteger("name1")+data2.getInteger("name1"));
        data3.put("name2",data1.getInteger("name2")+data2.getInteger("name2"));
        data3.put("name3",data1.getInteger("name3")+data2.getInteger("name3"));
        data3.put("name4",data1.getInteger("name4")+data2.getInteger("name4"));
        data3.put("name5",data1.getInteger("name5")+data2.getInteger("name5"));
        data3.put("name6",data1.getInteger("name6")+data2.getInteger("name6"));
        jsonObjects.add(data1);
        jsonObjects.add(data2);
        jsonObjects.add(data3);
        return jsonObjects;
    }

}
